﻿function WorkViewModel() {
    var self = this;

    self.interval = 5; //生成间隔
    self.UrlList = new Array();
    self.GatherState = -1; //采集状态
    self.NextCategoryUrl = "";
    self.StartUrlIndex = 0;
    self.GatherIds = "";//要被采集的Id
    self.GatherId = "";//正在被采集的Id
    self.ProgressNum = ko.observable(0);
    self.ProgressIgnoreNum = ko.observable(0);
    self.GatheringNum = 0;
    self.IgnoreNum = 0;
    self.thread = ko.observable(1);
    self.stoplog = ko.observable(false);
    self.LogErr = ko.observable(true);
    self.LogRight = ko.observable(false);
    self.LogAlert = ko.observable(false);
    self.MsgList = ko.observableArray();

    self.CurrentRowIndex = 0;
    //正常采集
    self.GatherMain = function () {
        $.ajax({
            type: "POST",
            url: "/Gather/GatherClassPage/",
            timeout: 6000000,
            data: {
                IDs: self.GatherIds,
                NextCategoryUrl: (self.NextCategoryUrl),
                IsReverse: $("#Reverse").is(":checked"),
                StartUrlIndex: self.StartUrlIndex
            },
            dataType: "json",
            success: function (info) {
                if (info.Errors !== "") {
                    self.Stop();
                    self.logger(info.GatheringUrl, "采集任务中止。<br />" + info.Errors, -1);
                    return;
                }
                self.NextCategoryUrl = info.NextCategoryUrl;
                self.StartUrlIndex = info.StartUrlIndex;
                self.GatherId = info.GatherId;

                self.logger(info.GatheringUrl, "正在采集" + info.Urls.length + "页。<br />下一栏目页是：" + info.NextCategoryUrl, -1);

                for (var i = 0; i < info.Urls.length; i++) {
                    self.UrlList.push(info.Urls[i]);
                }

                //开始采集
                if (self.GatherState !== -1)
                    self.GatherState = 1;
                self.CurrentRowIndex = 0;

                self.GatherWeb({
                    urls: self.GetUrl(self.CurrentRowIndex),
                    GatherId: info.GatherId
                });
            },
            error: function (msg) {
                self.Stop();
                self.logger(null, "内部服务器错误。" + msg.statusText, 0);
            }
        });
    }

    self.GetUrl = function (index) {
        var strArr = new Array();
        var j = index + self.thread();
        if (index + self.thread() > self.UrlList.length)
            j = self.UrlList.length;

        for (var i = index; i < j; i++) {
            strArr.push(self.UrlList[i]);
            self.CurrentRowIndex = i;
        }
        return strArr.join("|");
    }

    self.GatherWeb = function (args) {
        if (self.GatherState === -1) {
            self.logger(null, "用户停止采集.", 3);
            return;
        }

        if (args.urls === "" && self.NextCategoryUrl !== "") {
            self.GoGatheringNextClass();
            return;
        }

        if (args.urls.length === "" && self.NextCategoryUrl === "") {
            self.Stop();
            self.logger(null, "采集完成C.", 3);
            return;
        }


        $.ajax({
            type: "POST",
            url: "Gather/GatherWeb",
            timeout: 6000000,
            data: {
                GatherId: args.GatherId,
                URLs: args.urls,
                BadLinkNum: $("#BadLinkNum").val(),
                IsTest: $("#IsTest").is(":checked"),
                IsUpdate: $("#IsUpdate").is(":checked"),
                IsLeech: $("#IsLeech").is(":checked")
            },
            dataType: "JSON",
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                //IsStop();
                self.logger(null, "错误!" + xmlHttpRequest.statusText, 0);
                self.logger(null, "错误!" + textStatus.toString(), 0);
                self.logger(null, "错误!" + errorThrown.toString(), 0);
            },
            success: function (data) {

                if (Object.prototype.toString.call(data) === '[object Array]') {
                    for (var j = 0; j < data.length; j++) {
                        self.logger(data[j].URL, data[j].Messages, data[j].Type);

                        if (data[j].Gathered === true) {
                            self.GatheringNum++;
                        } else {
                            self.IgnoreNum++;
                        }
                    }
                } else {
                    self.logger(data.URL, data.Messages, data.Type);

                    if (data.Gathered === true) {
                        self.GatheringNum++;
                    } else {
                        //debugger
                        self.IgnoreNum++;
                    }
                }

                self.ProgressNum(self.GatheringNum);
                self.ProgressIgnoreNum(self.IgnoreNum);

                if ((self.NextCategoryUrl === "" && self.CurrentRowIndex === self.UrlList.length - 1)) {
                    self.Stop();
                }
                if (self.GatherState === -1 && self.CurrentRowIndex === 0) {
                    self.logger(null, "采集完成A.", -1);
                    return;
                }


                if (self.CurrentRowIndex < self.UrlList.length - 1) {
                    self.CurrentRowIndex++;

                    window.setTimeout(function (urls, gatherId) {
                        self.GatherWeb({
                            urls: urls,
                            GatherId: gatherId
                        });
                    }(self.GetUrl(self.CurrentRowIndex), args.GatherId), self.interval);
                }

                if (self.NextCategoryUrl !== "" && self.CurrentRowIndex === self.UrlList.length - 1) {
                    self.GoGatheringNextClass();
                }
            }
        });

    }

    // 重新采集一下页栏目页
    self.GoGatheringNextClass = function () {
        self.CurrentRowIndex = 0;
        self.UrlList = new Array();

        self.GatherMain();
    }

    self.Start = function () {
        self.GatherState = 1;
        self.UrlList = new Array();

        self.GatheringNum = 0;
        self.IgnoreNum = 0;
        self.StartUrlIndex = 0;
        self.ProgressNum(0);
        self.ProgressIgnoreNum(0);

        $('#btnstart').attr("disabled", true);
        $('#btnstop').removeAttr("disabled");

        self.logger(null, "开始采集。", 3);

        self.GatherMain();
    }

    self.Stop = function () {
        self.GatherState = -1;
        self.CurrentRowIndex = 0;
        self.UrlList = new Array();
        self.NextCategoryUrl = "";


        $("#btnstart").removeAttr("disabled");
        $("#btnstop").attr("disabled", true);
    }

    self.logger = function (url, info, type) {
        if (self.stoplog() === true) {
            return;
        }
        var today = new Date();
        var time = today.format('HH:mm:ss:fff');
        if (type === 0 && self.LogErr() === false) {
            return;
        }
        if (type === 1 && self.LogRight() === false) {
            return;
        }
        if (type === 2 && self.LogAlert() === false) {
            return;
        }
        if (typeof (url) !== typeof (undefined) && url !== null && url.length > 0)
            info = '<a href="' + url + '" target="_blank">' + url + '</a> <br />' + info;
        self.MsgList.unshift({
            time: time,
            url: url, info: info
        });
    }

    self.ClearLog=function() {
        self.MsgList.removeAll();
    }
}